﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.Mvc;
using Orange.Logistics.Infrastructure;
using Orange.Logistics.Models;
using Orange.Logistics.Services;
using System.Web.Security;
using System.Linq;
using System.Collections.Generic;
using System.Xml.Linq;

namespace Orange.Logistics.Controllers {
    public class SystemController : Controller {

        private readonly ISystemService systemService;
        private readonly IModuleService moduleService;

        public UserInfo CurrentUser {
            get { return Session["CurrentUserInfo"] as UserInfo; }
            set { Session["CurrentUserInfo"] = value; }
        }

        public SystemController(ISystemService systemService, IModuleService moduleService) {
            this.systemService = systemService;
            this.moduleService = moduleService;
        }

        public ActionResult Index() {
            if (CurrentUser == null) {
                return RedirectToAction("Login");
            }
            return View();
        }

        //Menu
        [Permission]
        public PartialViewResult GetMenu(bool frmDB) {
            IEnumerable<Menu> menus = null;
            if (frmDB) {
                UserInfo userinfo = Session["CurrentUserInfo"] as UserInfo;
                menus = moduleService.GetSysMenus(userinfo.RoleIDs);
            } else {
                menus = LoadMenuFromConfigXml();
            }

            return PartialView(menus);
        }

        private IEnumerable<Menu> LoadMenuFromConfigXml() {
            XDocument xdoc = XDocument.Load(Server.MapPath("~/menu.xml"));
            return xdoc
                    .Root
                    .Elements("menu")
                    .Select(m => new Menu {
                        //MenuIcon = m.Attribute("icon").Value,
                        //MenuNo = m.Attribute("controller").Value,
                        //MenuUrl = "~/" + m.Attribute("controller").Value + "/Index",
                        MenuName = m.Attribute("title").Value,
                        SubMenus = m.Elements("tab")
                                    .Select(t => new Menu {
                                        MenuIcon = t.Attribute("icon").Value,
                                        MenuNo = t.Attribute("controller").Value,
                                        MenuUrl = "~/" + t.Attribute("controller").Value + "/Index",
                                        MenuName = t.Attribute("title").Value,
                                    })
                    });
        }


        [Permission]
        public JsonResult GetButtons() {
            string menuNo = Request["MenuNo"];
            int[] roles = CurrentUser.RoleIDs;
            var data = systemService.GetButtons(roles, menuNo).ToList();
            return Json(data.Select(d => new { id = d.PermissionAction, text = d.PermissionName, icon = d.Icon }));
        }

        [Permission]
        public JsonResult GetCurrentUser() {
            return Json(CurrentUser, JsonRequestBehavior.AllowGet);
        }

        [Permission]
        public ActionResult ChangePassword() {
            return View();
        }

        [Permission]
        [HttpPost]
        public JsonResult ChangePassword(FormCollection forms) {
            string OldPassword = forms["OldPassword"].ToString();
            string NewPassword = forms["NewPassword"].ToString();
            string ConfirmPassword = forms["ConfirmPassword"].ToString();
            if (NewPassword == ConfirmPassword) {
                SysUser user = systemService.GetUser(CurrentUser.UserId, OldPassword);
                if (user != null) {
                    user.UserPassword = NewPassword;
                    systemService.SaveChanges();
                    return Json(true);
                }
            }
            return Json(false);
        }

        public ActionResult Login() {
            return View();
        }

        [HttpPost]
        public ActionResult Login(FormCollection forms) {
            string UserName = forms["UserName"].ToString();
            string Password = forms["Password"].ToString();
            string CheckCode = forms["CheckCode"].ToString();

            if (!string.Equals(CheckCode, Session["CheckCode"])) {
                ModelState.AddModelError("", "验证码不正确");
            } else {
                SysUser user = systemService.GetUser(UserName, Password);
                if (user == null) {
                    ModelState.AddModelError("", "用户名或密码不正确");
                } else {
                    CurrentUser = GetUserInfo(user);
                    FormsAuthentication.SetAuthCookie(UserName, false);
                    FormsAuthentication.RedirectFromLoginPage(UserName, false);
                }
            }
            return View();
        }
        private UserInfo GetUserInfo(SysUser user) {
            int[] roles = systemService.GetRolesByUser(user.UserId);
            return new UserInfo {
                UserId = user.UserId,
                RoleIDs = roles
            };
        }



        public void LogOff() {
            FormsAuthentication.SignOut();
            Session.Abandon();
            Session.Clear();
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            FormsAuthentication.RedirectToLoginPage();
        }

        public ActionResult GetImgVerifyChars() {
            string rndNum = Rnd.GetRandNum(4);
            Session["CheckCode"] = rndNum;

            Bitmap img = rndNum.ToImg();
            MemoryStream ms = new MemoryStream();
            img.Save(ms, ImageFormat.Png);
            img.Dispose();
            return File(ms.ToArray(), @"image/jpeg");
        }
    }
}
